<script setup lang="ts">
import CategoryPanel from './components/CategoryPanel.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import CustomNav from './components/CustomNav.vue'
import XtxSwiper from '@/components/XtxSwiper.vue'
import XtxGuess from '@/components/XtxGuess.vue'
import HotPanel from './components/HotPanel.vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/components'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import PageSkeleton from './components/PageSkeleton.vue'

// 获取首页轮播图
const BannerList = ref<BannerItem[]>([])
const getHomeBanner = async () => {
  let res = await getHomeBannerAPI()
  BannerList.value = res.result
}

// 获取首页前台分类
const CategoryList = ref<CategoryItem[]>([])
const getHomeCategory = async () => {
  let res = await getHomeCategoryAPI()
  CategoryList.value = res.result
}

// 获取首页热门推荐
const HotList = ref<HotItem[]>([])
const getHomeHot = async () => {
  let res = await getHomeHotAPI()
  HotList.value = res.result
}

// 触底函数
const guessRef = ref<XtxGuessInstance>()
const onScrolltolower = () => {
  guessRef.value?.getMore()
}

// 下拉刷新函数
const freshStatus = ref(false)
const onRefresh = async () => {
  // 开启下拉刷新
  freshStatus.value = true
  guessRef.value?.resetData()
  await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot(), guessRef.value?.getMore()])
  // 关闭下拉刷新
  freshStatus.value = false
}

// 判断是否在网络请求中
const loading = ref(true)
onLoad(async () => {
  loading.value = true
  await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot(), guessRef.value?.getMore()])
  loading.value = false
})
</script>
<template>
  <CustomNav />
  <scroll-view
    scroll-y
    class="scrollView"
    @scrolltolower="onScrolltolower"
    @refresherrefresh="onRefresh"
    refresher-enabled
    :refresher-triggered="freshStatus"
  >
    <PageSkeleton v-if="loading" />
    <template v-else>
      <XtxSwiper :BannerList="BannerList" />
      <CategoryPanel :CategoryList="CategoryList" />
      <HotPanel :HotList="HotList" />
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
  height: 100%;
}

.scrollView {
  flex: 1;
}
</style>
